package com.yuntsg.nnsfcp.controller.back;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuntsg.nnsfcp.common.beans.ResultBean;
import com.yuntsg.nnsfcp.common.utils.CheckUtil;
import com.yuntsg.nnsfcp.common.utils.StringUtil;
import com.yuntsg.nnsfcp.common.utils.UserUtil;
import com.yuntsg.nnsfcp.entity.BiaoshuEntity;
import com.yuntsg.nnsfcp.front.entity.BidBackCompare;
import com.yuntsg.nnsfcp.front.entity.BidDocumentArticle;
import com.yuntsg.nnsfcp.front.entity.BidDocumentRecordArticle;
import com.yuntsg.nnsfcp.front.mapper.*;
import com.yuntsg.nnsfcp.service.CommonService;
import com.yuntsg.nnsfcp.service.back.BackService;
import com.yuntsg.nnsfcp.util.CompareUtils;


import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import java.net.URLDecoder;
import java.time.LocalDateTime;

/**
 * @Author: 葛成瑞
 * @Date: 2024/9/26 10:07
 */
@RestController
@Slf4j
@RequestMapping("/back")
public class BackController {

    @Resource
    BidBackCompareMapper bidBackCompareMapper;

    @Resource
    BidDocumentRecordArticleMapper bidDocumentRecordArticleMapper;

    @Resource
    BidDocumentArticleMapper bidDocumentArticleMapper;

    @Resource
    FundTabMapper fundTabMapper;

    @Resource
    EmployeeMapper employeeMapper;

    @Resource
    CommonService commonService;

    @Resource
    UserUtil userUtil;

    @Resource
    BackService backService;


    //主要使用关于后台三种人员查看 菜单 目前只是 有管理员 馆员两种角色 可以使用

    //    @ApiOperation(value = "1 获取全部前台提交的论文标书")
    @GetMapping("/get-all-bid")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "type", value = "标书状态 1 已上传未提交 2 已反馈错误 3 已提交 4 检测中 5 检测完成"),
//            @ApiImplicitParam(name = "year", value = "年份"),
//            @ApiImplicitParam(name = "level", value = "级别"),
//            @ApiImplicitParam(name = "ins", value = "机构"),
//            @ApiImplicitParam(name = "bidType", value = "基金类别"),
//            @ApiImplicitParam(name = "proName", value = "项目名称"),
//            @ApiImplicitParam(name = "proNo", value = "项目编号"),
//            @ApiImplicitParam(name = "pep", value = "负责人"),
//            @ApiImplicitParam(name = "dep", value = "部门"),
//            @ApiImplicitParam(name = "acce", value = "参与者"),
//            @ApiImplicitParam(name = "limit", value = "数量"),
//            @ApiImplicitParam(name = "page", value = "页码")
//    })
    public ResultBean<Object> getAllBid(Integer type, Integer page, Integer limit,
                                        String year,
                                        String level,
                                        String ins,
                                        String bidType,
                                        String proName,
                                        String proNo,
                                        String pep,
                                        String acce) {
        // 年份、级别（国家级、省厅级）、机构（指受理机构，比如：国家自然科学基金）、类别（比如：面上项目）、项目名称、项目编号、申请人、部门、主要参与者等
        if (StringUtil.isNull(page) || StringUtil.isNull(limit)) {

            page = 1;
            limit = 10;
        }
        if (StringUtil.isNotNull(year)) {
            year = URLDecoder.decode(year);
        }
        if (StringUtil.isNotNull(level)) {
            level = URLDecoder.decode(level);
        }
        if (StringUtil.isNotNull(ins)) {
            ins = URLDecoder.decode(ins);
        }
        if (StringUtil.isNotNull(bidType)) {
            bidType = URLDecoder.decode(bidType);
        }
        if (StringUtil.isNotNull(proName)) {
            proName = URLDecoder.decode(proName);
        }
        if (StringUtil.isNotNull(proNo)) {
            proNo = URLDecoder.decode(proNo);
        }
        if (StringUtil.isNotNull(pep)) {
            pep = URLDecoder.decode(pep);
        }
        if (StringUtil.isNotNull(acce)) {
            acce = URLDecoder.decode(acce);
        }
        QueryWrapper<BidDocumentRecordArticle> stat = new QueryWrapper<>();
        if (StringUtil.isNotNull(type)) {
            stat = new QueryWrapper<BidDocumentRecordArticle>().eq("stat", type);
            if (StringUtil.isNotNull(year)) {
                stat = stat.like("year_range", year);
            }
            if (StringUtil.isNotNull(level)) {
                stat = stat.like("level", level);
            }
            if (StringUtil.isNotNull(ins)) {
                stat = stat.like("ins", ins);
            }
            if (StringUtil.isNotNull(bidType)) {
                stat = stat.eq("bidType", bidType);
            }
            if (StringUtil.isNotNull(proName)) {
                stat = stat.like("proName", proName);
            }
            if (StringUtil.isNotNull(proNo)) {
                stat = stat.eq("proNo", proNo);
            }
            if (StringUtil.isNotNull(pep)) {
                stat = stat.like("pep", pep);
            }
            if (StringUtil.isNotNull(acce)) {
                stat = stat.like("acce", acce);
            }

        }
        stat.orderByDesc("id");
        IPage iPage = new Page(page, limit);
        IPage iPage1 = bidDocumentRecordArticleMapper.selectPage(iPage, stat);
        commonService.addUserInfo(iPage1.getRecords());
        return new ResultBean<>(iPage1);
    }

    //    @ApiOperation(value = "1.1 设置当前国自然订单状态")
    @GetMapping("/up-bid-sta")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "type", value = " 1 查重进行中 2 检测完成 "),
//            @ApiImplicitParam(name = "id", value = "主键id"),
//
//    })
    public ResultBean<Object> getAllBid(Integer type, Integer id) {
        CheckUtil.check(StringUtil.isNotNull(type), "状态类型不能空");
        CheckUtil.check(StringUtil.isNotNull(id), "id状态类型不能空");
        BidDocumentRecordArticle bidDocumentRecordArticle = bidDocumentRecordArticleMapper.selectById(id);
        if (type == 1) {
            bidDocumentRecordArticle.setStat(4);
        } else {
            bidDocumentRecordArticle.setStat(5);
        }
        bidDocumentRecordArticle.setUpti(LocalDateTime.now());
        bidDocumentRecordArticleMapper.updateById(bidDocumentRecordArticle);
        return new ResultBean<>("");

    }

    @GetMapping("/compare-new-old")
//    @ApiOperation(value = "3 获取比较两个解析结果")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "bid", value = "标书id"),
//    })
    public ResultBean<Object> getCompareNewOld(Integer bid) {
        CheckUtil.check(StringUtil.isNotNull(bid), "bid is  not null");
        BidBackCompare bidBackCompare = bidBackCompareMapper.selectOne(new QueryWrapper<BidBackCompare>().eq("bid", bid));
        String org = bidBackCompare.getOrg();
        String modi = bidBackCompare.getModi();
        if (StringUtil.isNotNull(modi)) {
            BiaoshuEntity biaoshuEntity = JSONObject.parseObject(org, BiaoshuEntity.class);
            BiaoshuEntity biaoshuEntitymodi = JSONObject.parseObject(modi, BiaoshuEntity.class);
            String res = new CompareUtils<BiaoshuEntity>().compare(biaoshuEntity, biaoshuEntitymodi);
            if (StringUtil.isNotNull(res)) {
                String[] split = res.split(CompareUtils.COMMA);
                StringBuffer stringBuffer = new StringBuffer();
                for (String s : split) {
                    stringBuffer.append(s + "\r\n");
                }
                return new ResultBean<>(stringBuffer.toString());
            }
        } else {
            return new ResultBean<>("旧数据  程序未完善  请忽略比对");
        }
        return new ResultBean<>("系统提取的标书内容，未做任何修改");
    }


    //    @ApiOperation(value = "2 获取单个标书下面全部文章信息")
    @GetMapping("/get-all-bid-art")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "bidi", value = "标书id"),
//            @ApiImplicitParam(name = "page", value = "页码"),
//            @ApiImplicitParam(name = "limit", value = "数量")
//    })
    public ResultBean<Object> getAllBidArt(Integer bid, Integer page, Integer limit, String type) {
        if (StringUtil.isNull(page) || StringUtil.isNull(limit)) {
            page = 1;
            limit = 10;
        }
        if (StringUtil.isNull(bid)) {
            CheckUtil.check(false, "标书 bid 必传");
        }
        IPage iPage = new Page(page, limit);
        QueryWrapper<BidDocumentArticle> bdId = new QueryWrapper<BidDocumentArticle>().eq("bd_id", bid);

        if (StringUtil.isNotNull(type)) {
            bdId.eq("type", type);
        }

        IPage iPage1 = bidDocumentArticleMapper.selectPage(iPage, bdId);
        return new ResultBean<>(iPage1);
    }

    @PostMapping("/add-full-text-url")
//    @ApiOperation(value = "4.0上传当前文章全文路径")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "id", value = "标书文章id"),
//            @ApiImplicitParam(name = "path", value = "路径")
//    })
    public ResultBean<Object> addFullTextURL(@RequestBody com.yuntsg.nnsfcp.entity.RequestBody requestBody) {
//        Map<String, String[]> parameterMap = request.getParameterMap();
//        parameterMap.forEach((k,v)->{
//            System.out.println(k);
//            System.out.println(v);
//        });
//        log.info(parameterMap+"");
        log.info("bidaid" + requestBody.getId());
        log.info("path" + requestBody.getPath());
        CheckUtil.check(StringUtil.isNotNull(requestBody.getId()), "bidaid is  not null");
        CheckUtil.check(StringUtil.isNotNull(requestBody.getPath()), "path is  not null");
        BidDocumentArticle bidDocumentArticle = bidDocumentArticleMapper.selectById(requestBody.getId());
        boolean isExist = bidDocumentArticle == null;
        log.info(isExist + "");
        CheckUtil.check(bidDocumentArticle != null, "bidDocumentArticle is null");
        bidDocumentArticle.setFullUrl(requestBody.getPath());
        bidDocumentArticleMapper.updateById(bidDocumentArticle);
        return new ResultBean<>();

    }


    @PostMapping("/add-txt-pic-word")
//    @ApiOperation(value = "4上传文字或者图片报告")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "bidaid", value = "标书文章id"),
//            @ApiImplicitParam(name = "type", value = "1 是文字 2是图片"),
//            @ApiImplicitParam(name = "xstype", value = "学术不端类型 1 是[全网+篇内] 2 否 3 是[全网] 4 是[篇内]"),
//            @ApiImplicitParam(name = "path", value = "路径")
//    })
    public ResultBean<Object> addTxtPicWord(@RequestBody com.yuntsg.nnsfcp.entity.RequestBody requestBody) {
        log.info("bidaid+" + requestBody.getBidaid());
        log.info("type+" + requestBody.getType());
        log.info("xstype+" + requestBody.getXstype());
        log.info("path+" + requestBody.getPath());
        CheckUtil.check(StringUtil.isNotNull(requestBody.getBidaid()), "bidaid is  not null");
        CheckUtil.check(StringUtil.isNotNull(requestBody.getType()), "type is  not null");
        CheckUtil.check(StringUtil.isNotNull(requestBody.getPath()), "path is  not null");
        BidDocumentArticle bidDocumentArticle = bidDocumentArticleMapper.selectById(requestBody.getBidaid());
        CheckUtil.check(bidDocumentArticle != null, "bidDocumentArticle is null");
        if (requestBody.getType().equals("1")) {
            bidDocumentArticle.setTxtWord(requestBody.getPath());
            bidDocumentArticle.setTxtWordDf(1);
        } else {
            bidDocumentArticle.setPicWord(requestBody.getPath());
            bidDocumentArticle.setPicWordDf(1);
        }
        bidDocumentArticle.setAddt(LocalDateTime.now());
        bidDocumentArticle.setStat(1);
        bidDocumentArticle.setCheckTy(Integer.parseInt(requestBody.getXstype()));
        bidDocumentArticleMapper.updateById(bidDocumentArticle);
        return new ResultBean<>();

    }

    @PostMapping("/up-article-info")
//    @ApiOperation(value = "4.1更新文章信息")
    public ResultBean<Object> upArticleInfo(@RequestBody BidDocumentArticle bidDocumentArticle) {
        CheckUtil.check(bidDocumentArticle != null, "bidDocumentArticle is null");
        CheckUtil.check(bidDocumentArticle.getId() != null, "bidDocumentArticle id is null");
        bidDocumentArticleMapper.updateById(bidDocumentArticle);
        return new ResultBean<>();
    }

    @PostMapping("/up-check-word-res")
//    @ApiOperation(value = "4.2添加检测报告和检测备注")
    public ResultBean<Object> upCheckWordRes(@RequestBody BidDocumentRecordArticle bidDocumentRecordArticle) {
        CheckUtil.check(bidDocumentRecordArticle != null, "bidDocumentRecordArticle is null");
        CheckUtil.check(bidDocumentRecordArticle.getId() != null, "bidDocumentRecordArticle id is null");
        bidDocumentRecordArticle.setUpti(LocalDateTime.now());
        bidDocumentRecordArticleMapper.updateById(bidDocumentRecordArticle);
        return new ResultBean<>();

    }

    @PostMapping("/word-marking")
    //用于给报告打标记使用
    public ResultBean<Object> wordMarking(@RequestBody BidDocumentRecordArticle bidDocumentRecordArticle) {
        CheckUtil.check(bidDocumentRecordArticle != null, "bidDocumentRecordArticle is null");
        CheckUtil.check(bidDocumentRecordArticle.getResNote() != null, "bidDocumentRecordArticle resnote is null");
        bidDocumentRecordArticle.setUpti(LocalDateTime.now());
        bidDocumentRecordArticleMapper.updateById(bidDocumentRecordArticle);
        return new ResultBean<>();

    }

    @PostMapping("/up-many-files-res")
//    @ApiOperation(value = "4.3批量添加文件 压缩包进行")
    public ResultBean<Object> upManyFilesRes(MultipartHttpServletRequest request) {
        MultipartFile file = request.getFile("file");
        //年份
        String year = request.getParameter("year");
        // 级别
        String level = request.getParameter("level");
        //机构
        String ins = request.getParameter("ins");
        commonService.addManyFilesToRecord(file, year, level, ins);
        return new ResultBean<>();

    }


}



